/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.archivers.zip.zipEntryAndData;

import com.softwarecraftsmen.inputStreamReaders.CopyingInputStreamReader;
import com.softwarecraftsmen.inputStreamReaders.InputStreamReader;
import com.softwarecraftsmen.inputStreamReaders.ReadableData;
import com.softwarecraftsmen.inputStreams.ByteArrayBufferedInputStream;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.zip.ZipOutputStream;

public class ByteBackedZipEntryAndData implements ZipEntryAndData, ReadableData
{
	private final String qualifiedName;
	private final long modificationTimeInMillisecondsSinceEpoch;
	private final byte[] data;
	private static final int OneKilobyte = 1024;

	public ByteBackedZipEntryAndData(final @NotNull String qualifiedName, final long modificationTimeInMillisecondsSinceEpoch, final @NotNull byte[] data)
	{
		this.qualifiedName = qualifiedName;
		this.modificationTimeInMillisecondsSinceEpoch = modificationTimeInMillisecondsSinceEpoch;
		this.data = data;
	}

	public void write(final @NotNull ZipOutputStream outputStream) throws IOException
	{
		outputStream.putNextEntry(new ConvenientZipEntry(qualifiedName, modificationTimeInMillisecondsSinceEpoch));
		readData(new CopyingInputStreamReader(outputStream));
		outputStream.closeEntry();
	}

	@NotNull
	public String pathNameInsideZip()
	{
		return qualifiedName;
	}

	@NotNull
	public <T> T readData(final @NotNull InputStreamReader<T> inputStreamReader)
	{
		return new ByteArrayBufferedInputStream(data).readData(inputStreamReader);
	}
}
